package com.supreme.orderserver.service;

import com.supreme.common.dto.UpdateGoodsStockDTO;
import com.supreme.commonboot.exception.BizException;
import com.supreme.commonentity.mysql.primary.BizStock;
import com.supreme.commonmybatis.mapper.StockMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class StockService {

    @Resource
    private StockMapper stockMapper;

    @Transactional(rollbackFor = BizException.class)
    public void updateGoodsStock(UpdateGoodsStockDTO updateGoodsStockDTO) {
        final Long goodsId = updateGoodsStockDTO.getGoodsId();
        final Integer goodsNum = updateGoodsStockDTO.getGoodsNum();

        final BizStock stock = stockMapper.selectById(goodsId);
        if (Objects.isNull(stock)) {
            throw new BizException("stock not found");
        }

        if (goodsNum > stock.getStockNum()) {
            throw new BizException("stock num not enough");
        }

        stock.setStockNum(stock.getStockNum() - goodsNum);
        stockMapper.updateById(stock);
    }
}
